package com.thx.common.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.util.ThreadLocalContext;
import com.thx.common.web.Page;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述 : 翻页拦截器，负责处理页面传入的翻页参数，并将查询的结果集封装后返回页面.
 *
 * @author 贾红磊
 */
public class PageInterceptor extends MethodFilterInterceptor {

  private static final long serialVersionUID = -8695848489369824219L;

  private static final Logger LOG = LoggerFactory.getLogger(PageInterceptor.class);

  private static int perPage = 15; // 默认每页最多显示15条数据

  public void init() {
    // 从配置文件读入每页最多显示数据条数
    PageInterceptor.perPage = AppContext.getPerPage();
  }

  private int string2Int(String valStr, int defaultValue) {
    try {
      return Integer.valueOf(valStr);
    } catch (Exception ex) {
      return defaultValue;
    }
  }

  @Override
  protected String doIntercept(ActionInvocation invocation) throws Exception {
    LOG.debug("拦截住一个翻页方法，并开始处理翻页参数......");

    Object action = invocation.getAction();
    CurdAction baseAction;
    Page page;
    HttpServletRequest request;

    if (action instanceof CurdAction) {
      request = ServletActionContext.getRequest();
      request.setAttribute("pageTag.request_uri", request.getRequestURI());
      String goPageStr = request.getParameter("pageNo"); // 从页面取到要到第几页去，页面参数为pageNO或者goPage
      if (StringUtils.isEmpty(goPageStr)) {
        goPageStr = request.getParameter("goPage"); // 从页面取到要到第几页去，页面参数为pageNO或者goPage
      }

      String perPageStr = request.getParameter("perPage");// 从页面取到每页显示几条

      int goPage = 1;
      int perPage = PageInterceptor.perPage;

      if (!StringUtils.isEmpty(perPageStr))
        perPage = string2Int(perPageStr, PageInterceptor.perPage);

      if (!StringUtils.isEmpty(goPageStr))
        goPage = string2Int(goPageStr, 1);

      page = new Page(goPage, perPage);
      ThreadLocalContext.set("page", page);
      ThreadLocalContext.set("perPage", perPage);
      baseAction = (CurdAction) action;
      baseAction.setPage(page);
    }

    String result = invocation.invoke();

    LOG.debug("拦截翻页方法已调用完成，返回页面。");
    return result;
  }
}
